package org.cogaen.sound;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @class LoopingByteInputStream
 * @author Florian Lettner
 * 
 * Provides and byte input stream that can be looped multiple times.
 */
public class LoopingByteInputStream extends ByteArrayInputStream {
	
	/** A flag to indicate if the input stream is closed. */
	private boolean closed;

	/**
	 * Creates a new loopable input stream.
	 * 
	 * @param buffer The buffer carrying the stream data.
	 */
	public LoopingByteInputStream(byte[] buffer) {
		super(buffer);
		closed = false;
	}
	
	/**
	 * Processes the stream.
	 * 
	 * @param buffer The buffer carrying the stream data.
	 * @param An offset to be applied.
	 * @param The stream length.
	 */
	@Override
	public int read(byte[] buffer, int offset, int length) {
		if (closed) return -1;
		int totalBytesRead = 0;
		while (totalBytesRead < length) {
			int numBytesRead = super.read(buffer, offset + totalBytesRead, length - totalBytesRead);
			if (numBytesRead > 0) totalBytesRead += numBytesRead;
			else { 
				reset();
				
			}
		} 
		return totalBytesRead;
	
	}

	/**
	 * Closes the stream.
	 * 
	 * @throws IOException
	 */
	@Override
	public void close() throws IOException {
		super.close();
		closed = true;
	}

}
